package com.zjitc.controller;



import com.zjitc.common.PageModel;
import com.zjitc.pojo.*;
import com.zjitc.service.CategoryService;
import com.zjitc.utils.Utils;
import com.zjitc.common.ServerResponse;
import com.zjitc.service.OrderService;
import com.zjitc.service.ProductService;
import com.zjitc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * Create By IntelliJ IDEA
 *
 * @author:
 * @create-Time: 2017/12/19  11:48
 */
@Controller
@RequestMapping("/admin")
public class AdminController {

  @Autowired
  private UserService userService;
  @Autowired
  private ProductService productService;
  @Autowired
  private OrderService orderService;
  @Autowired
  private CategoryService categoryService;

  private static final int COUNT = 10;
  private static final String ADMIN = "admin";
  private static String PAGE = "page";
  private static String USER = "user";
  private static String PRODUCT = "product";
  private static String CATEGORY = "list";
  private static String IS_HOT = "isHot";

  @RequestMapping("gotoAdminLogin")
  public String gotoAdminLogin() {
    return "admin/index";
  }

  @RequestMapping("/gohome")
  public String adminLogin(String username, String password, HttpSession session,
      RedirectAttributes attributes)
      throws ServletException, IOException, NoSuchAlgorithmException {
    User user = userService.adminLogin(username, password);
    if (user != null) {
      session.setAttribute(ADMIN, user);
      return "/admin/home";
    }
    return "redirect:/index.do";
  }

  @RequestMapping("/adminOut")
  @ResponseBody
  public ServerResponse adminOut(HttpSession session)
      throws IOException, ServletException {
    session.removeAttribute(ADMIN);
    return ServerResponse.createSuccess();
  }

  //user
  @RequestMapping("/adminFindAllUser")
  public ModelAndView useradminFindall(@RequestParam(value = "page") String pageid)
      throws ServletException, IOException {
    ModelAndView modelAndView = new ModelAndView();
    PageModel<User> pageModel = userService.findall(Integer.parseInt(pageid), COUNT);
    modelAndView.addObject(PAGE, pageModel);
    modelAndView.setViewName("/admin/user/list");
    return modelAndView;
  }

  @RequestMapping("/userGoEdit")
  public ModelAndView goEdit(@RequestParam("uid") String uid, @RequestParam("page") String page)
      throws ServletException, IOException {
    User user = userService.findbyuid(uid);
    ModelAndView modelAndView = new ModelAndView("/admin/user/edit");
    modelAndView.addObject(USER, user);
    modelAndView.addObject(PAGE, page);
    return modelAndView;
  }

  @RequestMapping("/adminUpdate")
  public String useradminUpdate(User user)
      throws IOException, NoSuchAlgorithmException, ServletException {
    userService.update(user);
    return "redirect:/admin/adminFindAllUser.do?page=0";


  }

  @RequestMapping("/adminDeleteUser")
  public String useradminDelete(String uid)
      throws IOException, ServletException {
    userService.deluser(uid);
    return "redirect:/admin/adminFindAllUser.do?page=0";
  }

  @RequestMapping("/adminFindAllProduct")
  public ModelAndView productadminFindall(@RequestParam("page") String pageid)
      throws ServletException, IOException {
    ModelAndView m = new ModelAndView("/admin/product/list");
    PageModel<Product> page = productService.findAllProduct(Integer.parseInt(pageid), COUNT);
    m.addObject(PAGE, page);
    return m;
  }

  @RequestMapping("/productGoEdit")
  public ModelAndView productGoEdit(String pid, @RequestParam("pageid") String pageid)
      throws ServletException, IOException {
    ModelAndView m = new ModelAndView("/admin/product/edit");
    Product product = productService.findbyid(pid);
    List<Category> list = categoryService.adminfindAll();
    Map<String, String> map = new HashMap<>();
    list.forEach(item -> {
      map.put(item.getCid(), item.getCname());
    });
    Map<Integer, String> ishot = new HashMap<>();
    ishot.put(0, "否");
    ishot.put(1, "是");
    m.addObject(IS_HOT, ishot);
    m.addObject(PRODUCT, product);
    m.addObject(CATEGORY, map);
    m.addObject(PAGE, pageid);
    return m;
  }

  @RequestMapping("/productGoAdd")
  public ModelAndView priductgoadd(HttpServletRequest request)
      throws ServletException, IOException {
    ModelAndView modelAndView = new ModelAndView("/admin/product/add");
    List<Category> list = categoryService.adminfindAll();
    modelAndView.addObject("list", list);
    return modelAndView;
  }

  @RequestMapping("/adminProductUpdate")
  @ResponseBody
  public ServerResponse adminproductUpdate(Product product, HttpServletRequest request,
      HttpServletResponse response)
      throws IOException {
    Date date = new Date();
    System.out.println(product);
    product.setDate(date);
    if (!"".equals(product.getImage())) {
      String[] split = product.getImage().split("\\\\");
      product.setImage("products/1/" + split[2]);
    } else {
      product.setImage(null);
    }
    int update = productService.updateProduct(product);
    if (update == 1) {
      return ServerResponse.createSuccess();
    }
    return ServerResponse.createError();
  }

  @RequestMapping(value = "/adminProductAdd",method = RequestMethod.POST)
  @ResponseBody
  public ServerResponse<Product> adminproductAdd(Product product)
      throws ServletException, IOException {

    if (!"".equals(product.getImage())) {
      String[] split = product.getImage().split("\\\\");
      product.setImage("products/1/" + split[2]);
    } else {
      product.setImage(null);
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date date = new Date();
    int flag = 0;
    String newpid = Utils.code();
    product.setDate(date);
    product.setFlag(flag);
    product.setPid(newpid);
    int i = productService.addproduct(product);
    return ServerResponse.createSuccess(String.valueOf(i));
  }

  @RequestMapping("adminDeleteProduct")
  public String adminproductDelete(String pid)
      throws ServletException, IOException {
    productService.deleteByPid(pid);
    return "redirect:/admin/adminFindAllProduct.do?page=0";
  }

  //------------------------------------库存--------------------------------------------------------------
  @RequestMapping("adminCheckInventory")
  public ModelAndView adminCheckInventory(@RequestParam("page")String pageid) {
    ModelAndView modelAndView = new ModelAndView("/admin/product/inventory");
    PageModel<Product> page = productService.findAllProduct(Integer.parseInt(pageid), COUNT);
    modelAndView.addObject("page",page);
    return modelAndView;
  }

  @RequestMapping("adminUpdateInventory")
  @ResponseBody
  public ServerResponse adminUpdateInventory(@RequestParam("pid")String pid,@RequestParam("inventory")String count){
    int update = productService.updateInventory(pid,Integer.parseInt(count));
    return ServerResponse.createSuccess(String.valueOf(update));
  }

  //order
  @RequestMapping("adminFindAllOrder")
  public ModelAndView adminFindAllOrder(
      @RequestParam(value = "page", required = false, defaultValue = "1") Integer pageid)
      throws ServletException, IOException {
    ModelAndView modelAndView = new ModelAndView("/admin/order/list");
    PageModel<Orders> page = orderService.findAllOrder(pageid, COUNT);
    modelAndView.addObject("page", page);
    return modelAndView;
  }

  @RequestMapping("adminFindItem")
  public ModelAndView adminFindItem(String oid, HttpSession session)
      throws ServletException, IOException {
    ModelAndView modelAndView = new ModelAndView("/admin/order/orderitem");
    User user = (User) session.getAttribute(USER);
    Orders order = orderService.findOrderFromRedis(user.getUid(), oid);
    modelAndView.addObject("order", order);
    return modelAndView;
  }


  //category
  @RequestMapping("adminFindAllCategory")
  public ModelAndView categoryadminFindall()
      throws ServletException, IOException {
    ModelAndView modelAndView = new ModelAndView("/admin/category/list");
    List<Category> list = categoryService.adminfindAll();
    modelAndView.addObject("list", list);
    return modelAndView;
  }

  @RequestMapping("goCategoryEdit")
  public ModelAndView gocategoryedit(Category category) {
    ModelAndView modelAndView = new ModelAndView("/admin/category/edit");
    String cname = "cname";
    String item2 = "cid";
    modelAndView.addObject(cname, category.getCname());
    modelAndView.addObject(item2, category.getCid());
    return modelAndView;
  }

  @RequestMapping("goAddCategory")
  public String goallcategory() {
    return "/admin/category/add";
  }

  @RequestMapping("addCategory")
  public String addcategory(Category category)
      throws ServletException, IOException {
    List<Category> allcate = categoryService.adminfindAll();
    int count = allcate.size();
    String cid = String.valueOf(count + 1);
    category.setCid(cid);
    int cou = categoryService.add(category);
    return "redirect:/admin/adminFindAllCategory.do";
  }

  @RequestMapping("adminCategoryUpdate")
  public String adminCategoryupdate(Category category)
      throws ServletException, IOException {
    categoryService.update(category);
    return "redirect:/admin/adminFindAllCategory.do";
  }

  @RequestMapping("adminCategoryDelete")
  public String adminCategorydelete(String cid)
      throws ServletException, IOException {
    categoryService.deletebycid(cid);
    return "redirect:/admin/adminFindAllCategory.do";
  }
}
